package com.springcloud.music.demo.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpRequest;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @ Author      : cyw
 * @ Date        : created in  下午6:17 2021/4/22
 * @ Description :
 * @ Modified By :
 * @Version : $
 */
@Component
public class AccessFilter extends ZuulFilter {
    @Override
    public String filterType() {

        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 1;
    }

    @Override
    public boolean shouldFilter() {
        //对指定的serviceid过滤，如果要过滤所有服务，直接返回 true
        RequestContext context = RequestContext.getCurrentContext();
        String serviceId = (String)  context.get(FilterConstants.SERVICE_ID_KEY);
        if (serviceId.equals("user-service")){
            return true;
        }else if (serviceId.equals("singer-service")){
            return true;
        }

        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = request.getParameter("token");
        if (token == null){
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(200);
            context.setResponseBody("失败");
        }
        return null;
    }
}
